# ------------------------------------------------------------------------------------------------
### Generate Figure 7: Trends in overall, opposition, and government turnout
# ------------------------------------------------------------------------------------------------

# Load data
load("../data/processed/LGBTQ_election_data.Rda") 

# Filter data (exclude Warsaw)
LGBTQ_election_data <- LGBTQ_election_data %>%
  filter(id_county != 1465)

# Define outcomes for analysis
outcomes <- list(
  turnout = list(
    var = "turnout",
    label = "Overall Turnout",
    y_breaks = seq(20, 60, 10),
    y_limits = c(20, 60),
    color = "navyblue"
  ),
  opposition_turnout = list(
    var = "non_pis_support",
    label = "Opposition Turnout", 
    y_breaks = seq(10, 50, 10),
    y_limits = c(10, 50),
    color = "navyblue"
  ),
  government_turnout = list(
    var = "pis_support",
    label = "Government Turnout",
    y_breaks = seq(0, 40, 10), 
    y_limits = c(0, 40),
    color = "darkblue"
  )
)

# Function to create synthetic control plot for a given outcome
create_synthdid_plot <- function(data, outcome_config) {
  # Estimate SDID
  sc_did <- data %>% select(id, eyear, !!sym(outcome_config$var), treat)
  setup <- panel.matrices(as.data.frame(as_tibble(sc_did)))
  estimates <- synthdid_estimate(setup$Y, setup$N0, setup$T0)
  
  # Calculate control averages
  control_data <- data %>%
    filter(any_level_any_type == 0) %>%
    group_by(eyear) %>%
    summarise(!!sym(outcome_config$var) := mean(!!sym(outcome_config$var), na.rm = TRUE)) %>%
    mutate(outcome = outcome_config$label)
  
  # Create plot
  synthdid_plot_custom(estimates, se.method = 'jackknife') +
    # Add control averages
    geom_line(data = control_data, 
              aes(x = eyear, y = !!sym(outcome_config$var), color = "(Unweighted) Control"),  
              linetype = "dotted", size = 1.2) +
    geom_point(data = control_data, 
               aes(x = eyear, y = !!sym(outcome_config$var), color = "(Unweighted) Control", 
                   shape = "(Unweighted) Control"), size = 3) + 
    # Styling
    scale_color_manual(
      values = c(outcome_config$color, "#D9534F", "grey"),  
      labels = c("Synthetic Control", "Treated", "(Unweighted) Control")
    ) +  
    scale_shape_manual(values = c(17, 15, 16)) +  
    scale_y_continuous(
      breaks = outcome_config$y_breaks, 
      limits = outcome_config$y_limits, 
      oob = rescale_none
    ) +
    scale_x_continuous(breaks = unique(data$eyear)) +
    facet_grid(cols = vars(outcome_config$label), scales = "free") +
    geom_vline(xintercept = 2018.2, linetype = "dashed") +
    ylab("Percentage") +
    # Legend
    guides(color = guide_legend(override.aes = list(
      shape = c(17, 15, 16),  
      linetype = c("solid", "solid", "dotted")
    )),  
    shape = "none", linetype = "none") +
    theme_bw() +
    theme(
      legend.position = "bottom",
      legend.title = element_blank(),
      panel.grid.major.y = element_blank(),
      panel.grid.minor.y = element_blank(),
      panel.grid.minor.x = element_blank(),
      plot.title = element_blank(),
      axis.title.x = element_blank(),
      text = element_text(size = 23)
    )
}

# Generate all plots
plots <- lapply(outcomes, function(outcome) {
  create_synthdid_plot(LGBTQ_election_data, outcome)
})

# Combine plots vertically
trends_turnout_vertical <- ggarrange(
  plots$turnout, 
  plots$opposition_turnout, 
  plots$government_turnout,
  nrow = 3, 
  legend = "bottom", 
  common.legend = TRUE
)

# Save the combined plot
ggsave("../output/plots/figure7.pdf", width = 14, height = 18, dpi = 700)
